import { apiChangeUserInfo, apiResetPassword } from '@/api/user'
import { useErrMessage, useInfoMessage } from '@/utils/message'

Page({
  data: {
    userInfo: null,
    isEditing: false,
    tempUsername: "", // 临时存储编辑中的姓名
    isSubmit: false,

    yPasswordVisible: false,
    xPasswordVisible: false,
    password: "",
    newPassword: ""
  },
  onYClear() {
    this.onYPasswordInput({ detail: { value: '' } }); 
  },
  onXClear() {
    this.onXPasswordInput({ detail: { value: '' } }); 
  },
  async resetPassword() {
    const { password, newPassword } = this.data
    const data = await apiResetPassword({ password, newPassword })
    if (data.code === 200) {
      wx.setStorageSync('userInfo', this.data.userInfo)
      useInfoMessage(this, "修改成功")

      // 保留网页信息，其他删掉
      const websiteInfo=wx.getStorageSync("websiteInfo")
      wx.clearStorageSync()
      wx.setStorageSync('websiteInfo', websiteInfo)

      setTimeout(() => {
        wx.reLaunch({ url: '/pages/index/index' });
      }, 2000);
    } else {
      useErrMessage(this, data.msg)
    }
  },

  changeSubmit() {
    const { password, newPassword } = this.data
    if (password !== "" && newPassword !== "") {
      this.setData({ isSubmit: true })
    } else {
      this.setData({ isSubmit: false })
    }
  },

  onYPasswordInput(e) {
    this.setData({
      password: e.detail.value,  // 更新数据
    });
    this.changeSubmit();
  },
  onXPasswordInput(e) {
    this.setData({
      newPassword: e.detail.value,  // 更新数据
    });
    this.changeSubmit();
  },
  // 密码的可见性
  toggleYPasswordVisibility() {
    this.setData({
      yPasswordVisible: !this.data.yPasswordVisible,
    });
  },
  toggleXPasswordVisibility() {
    this.setData({
      xPasswordVisible: !this.data.xPasswordVisible,
    });
  },



  onLoad() {
    let userInfo = wx.getStorageSync('userInfo')
    if (userInfo){
      this.setData({
        userInfo: userInfo,
        tempUsername: userInfo.username
      });
    }else{
      // 未登录先去登录
      wx.navigateTo({
        url: '/pages/login/index',
      })
    }
    
  },


  // 切换编辑状态
  async toggleEdit() {
    if (this.data.isEditing) {
      // 保存逻辑
      this.setData({
        'userInfo.username': this.data.tempUsername,
        isEditing: false
      });

      const data = await apiChangeUserInfo(this.data.userInfo)
      if (data.code === 200) {
        wx.setStorageSync('userInfo', this.data.userInfo)
        useInfoMessage(this, "修改成功")
        setTimeout(() => {
          wx.navigateBack()
        }, 2000);
      } else {
        useErrMessage(this, data.msg)
      }
    } else {
      // 进入编辑状态
      this.setData({
        isEditing: true
      });
    }
  },

  // 输入框内容变化
  onUsernameInput(e) {
    this.setData({
      tempUsername: e.detail.value
    });
  }
});